﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Navigation;
using Windows.Phone.Storage.SharedAccess;

namespace Putta.KeyPass
{
    internal class PageUriMapper : UriMapperBase
    {
        public override Uri MapUri(Uri uri)
        {
            string path, query;
            Dictionary<string, string> parameters;

            // Get Path and Query.
            if (uri.IsAbsoluteUri)
            {
                path = uri.AbsolutePath;
                query = uri.Query;
            }
            else
            {
                string original = uri.ToString();
                int startQuery = original.IndexOf('?');

                if (startQuery == -1)
                {
                    path = original;
                    query = null;
                }
                else
                {
                    path = original.Substring(0, startQuery);
                    query = (startQuery == (original.Length - 1)) ? null : original.Substring(startQuery + 1);
                }
            }

            if (string.IsNullOrWhiteSpace(path))
                path = string.Empty;

            // Parse Query.
            if (query != null)
            {
                string[] pairs = query.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                parameters = new Dictionary<string, string>(pairs.Length);

                for (int i = 0; i < pairs.Length; i++)
                {
                    string pair = pairs[i];
                    int sep = pair.IndexOf('=');

                    if (sep == -1)
                        parameters[pair] = string.Empty;
                    else
                        parameters[pair.Substring(0, sep)] = pair.Substring(sep + 1);
                }
            }
            else
                parameters = new Dictionary<string, string>();

            // Perform Mapping.
            if (path == "/FileTypeAssociation")
            {
                string fileId, fileType;

                if (!parameters.TryGetValue("fileToken", out fileId))
                    return new Uri("/OpenDatabasePage.xaml", UriKind.Relative);

                fileType = Path.GetExtension(SharedStorageAccessManager.GetSharedFileName(fileId));

                if (fileType.Equals(".kdbx", StringComparison.CurrentCultureIgnoreCase))
                    return new Uri("/MainPage.xaml?FileToken=" + fileId, UriKind.Relative);
                else
                    return new Uri("/OpenDatabasePage.xaml", UriKind.Relative);
            }
            else
                return uri;
        }
    }
}
